package com.luckyframe.project.jmeter.websocket;

import com.luckyframe.common.constant.GlobalConsts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;
import org.springframework.web.socket.sockjs.client.SockJsClient;
import org.springframework.web.socket.sockjs.client.Transport;
import org.springframework.web.socket.sockjs.client.WebSocketTransport;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
public class WebSocketManager implements InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketManager.class);

    private volatile StompSession session;

    private WebSocketStompClient stompClient;

    @Autowired
    private Environment environment;

    public static final String SEND_URL = GlobalConsts.APP_PREFIX + GlobalConsts.HELLO_MAPPING;

    public static final String STATISTIC_URL = GlobalConsts.APP_PREFIX + GlobalConsts.STATISTIC_MAPPING;


    @Override
    public void afterPropertiesSet() throws Exception {

        WebSocketClient simpleWebSocketClient = new StandardWebSocketClient();
        List<Transport> transports = new ArrayList<>(1);
        transports.add(new WebSocketTransport(simpleWebSocketClient));

        SockJsClient sockJsClient = new SockJsClient(transports);
        stompClient = new WebSocketStompClient(sockJsClient);
        stompClient.setMessageConverter(new MappingJackson2MessageConverter());


    }


    public void publishGraphData(String msg){

         getOrCreateSession();

        if(this.session ==null){
            return;
        }

        synchronized (session){
            this.session.send(SEND_URL,msg);
        }

        logger.info("publishGraphData data @{}", LocalDateTime.now());

    }


    //plan 执行的统计数据
    public void publishStatisticData(String msg){

        getOrCreateSession();

        if(session==null){
            return;
        }

       synchronized (session){
           session.send(STATISTIC_URL,msg);
       }

        logger.info("publishStatisticData data @{}", LocalDateTime.now());

    }


    private StompSession getOrCreateSession() {
        if (session == null || !session.isConnected()) {
            String url = "ws://localhost:" + environment.getProperty("server.port") + GlobalConsts.ENDPOINT;
            try {
                session = stompClient.connect(url, new CustomStopSessionHandler()).get();
                return session;
            } catch (Exception e) {
                logger.error("publishPlanData connection failed return", e);
                return null;
            }
        }else {

            return session;
        }
    }




}
